import React, { useState, useEffect, useRef } from 'react'
import './index.modules.scss'
import SearchView from '@/components/searchView/index'
import { baseURL } from '@/http/request'
import { cityData } from '@/components/js/addressOptions'
import { useNavigate } from 'react-router-dom'
import {
  Space,
  Table,
  Button,
  Modal,
  Card,
  message,
  Input,
  Popconfirm,
  Pagination,
  Image,
  Form,
  Cascader,
  DatePicker,
  Upload,
  Col,
  Select,
  Row
} from 'antd'

import { PlusOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'
import {
  carOwnerInsuranceAdd,
  carOwnerInsuranceDelete,
  carOwnerListAll
} from '@/http/api/carOwner'
import {
  insuranceApplyList,
  insuranceApplyChange,
  insuranceCreateExcel,
  insuranceSerach,
  insuranceApplyDetils,
  insuranceDetils,
  insuranceChange,
  insuranceApplyDelete,
  insuranceApplyChangeStatus
} from '@/http/api/insurance'
import dayjs from 'dayjs'
const { TextArea } = Input
let pageData = {
  page: 1,
  size: 10,
  total: 0,
  appid: localStorage.getItem('appid')
}
const { RangePicker } = DatePicker
let _id = ''
let typeList = [
  {
    title: '保险编号',
    type: 'inpute',
    model: 'filmNo'
  }
]
let selectedRowsdata = []
let appid = localStorage.getItem('appid')
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
    carOwnerListFn()
  }, [])
  const handleChildMethod = () => {
    getList()
    carOwnerListFn()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const Navigate = useNavigate()
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, setIsShowAdd] = useState(false)
  const [isShowDetils, setisShowDetils] = useState(false)
  const [opposeRemarkSohw, setopposeRemarkSohw] = useState(false)
  const [deliverShow, setdeliverShow] = useState(false)
  const [isImgShow, setIsImgShow] = useState(false)
  const [detilsData, setDetilsData] = useState({
    filmName: '',
    carName: '',
    startTime: '',
    price: '',
    carOwnerName: '',
    carOwnerPhone: ''
  })
  const [detilsDataApply, setDetilsDataApply] = useState({})
  const [magnifyImg, setMagnifyImg] = useState('')
  const [fileList, setFileList] = useState([])
  const [optionsCarOwner, setOptionsCarOwner] = useState([])
  const [deliverId, setdeliverId] = useState('')
  const columns = [
    {
      title: '上传时间',
      dataIndex: 'create_time',
      align: 'center',
      render: (create_time) => {
        return <div>{dayjs(create_time).format('YYYY-MM-DD HH:mm:ss')}</div>
      }
    },
    {
      title: '投保人姓名',
      dataIndex: 'carOwnerName',
      align: 'center',
      minWidth: 2000
    },

    {
      title: '保单号',
      dataIndex: 'warrantyNum',
      align: 'center'
    },
    {
      title: '联系方式',
      dataIndex: 'carOwnerPhone',
      align: 'center'
    },

    {
      title: '状态',
      dataIndex: '',
      align: 'center',
      render: (data) => {
        if (data.status == 0) {
          return <span> 待理赔</span>
        } else if (data.status == 1) {
          return <span>理赔通过</span>
        } else {
          return <span style={{ color: 'red' }}> 理赔驳回</span>
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            onClick={async () => {
              let res = await insuranceApplyDetils({
                _id: data._id,
                appid: localStorage.getItem('appid')
              })
              let res2 = await insuranceDetils({
                _id: data.insuranceId,
                appid: localStorage.getItem('appid')
              })
              setisShowDetils(true)
              let changeData = { ...data }
              if (res.data.res) {
                setDetilsDataApply(res.data.res)
              }
              if (res2.data.res) {
                setDetilsData(res2.data.res)
              }
            }}
          >
            详情
          </Button>
          <Button
            type="primary"
            onClick={() => {
              showModalAdd(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedRowsdata = selectedRows.map((item) => {
        return item._id
      })
    }
  }

  // 获取列表
  const getList = async () => {
    const res = await insuranceApplyList(pageData)
    console.log(res)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id,
          images: JSON.parse(item.images)
        }
      })
    )
    pageData.total = res.data.total
  }
  // 获取所有
  const carOwnerListFn = async () => {
    let data = {
      appid
    }
    let res = await carOwnerListAll(data)
    setOptionsCarOwner([
      ...res.data.res.map((item) => {
        return {
          value: item._id,
          label: item.name
        }
      })
    ])
  }
  // 点击确定修改
  const onFinish = async (data) => {
    data.images = fileList
    data.appid = localStorage.getItem('appid')
    let res = ''
    if (_id) {
      data._id = _id
      data.images = JSON.stringify(data.images)
      data.res = await insuranceApplyChange(data)
    }

    messageApi.success(res.data.message)
    getList()
    setIsShowAdd(false)
    _id = ''
    form.resetFields()
  }
  // 拒绝理赔
  const onFinishOpposeRemark = async (data) => {
    let Updata = {
      ...data,
      _id: detilsDataApply._id,
      status: 2
    }
    let res = await insuranceApplyChange(Updata)
    setopposeRemarkSohw(false)
    messageApi.success(res.data.message)
    getList()
  }
  // 发货
  const onFinishTrackingNumber = async (data) => {
    console.log(11)
    let Updata = {
      ...data,
      _id: deliverId
    }
    let res = await insuranceApplyChange(Updata)
    await insuranceChange({
      _id: detilsData._id,
      product: detilsData.product - data.compensateNumber
    })
    setdeliverShow(false)
    messageApi.success(res.data.message)
    getList()
  }
  const showModalAdd = async (value) => {
    let changeData = { ...value }
    if (value._id) {
      let res = await insuranceApplyDetils({
        _id: value._id,
        appid: localStorage.getItem('appid')
      })
      let res2 = await insuranceDetils({
        _id: value.insuranceId,
        appid: localStorage.getItem('appid')
      })
      if (res.data.res) {
        setDetilsDataApply(res.data.res)
      }
      if (res2.data.res) {
        setDetilsData(res2.data.res)
      }
      form.setFieldsValue(res.data.res)
      _id = value._id
    }
    setIsShowAdd(true)
  }
  // 确认理赔
  const configApplyFn = async () => {
    let data = {
      status: 1,
      _id: detilsDataApply._id,
      insuranceId: detilsDataApply.insuranceId,
      compensateNumber: detilsDataApply.compensateNumber
    }

    let res = await insuranceApplyChangeStatus(data)
    setisShowDetils(false)
    getList()
    messageApi.success(res.data.message)
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await insuranceApplyDelete({ _id: data._id })
    messageApi.success(res.data.message)
    getList()
  }
  // 导出
  const exportExcel = async () => {
    let data = {}
    if (selectedRowsdata.length == 0) {
      data = {
        id: 'all',
        appid
      }
    } else {
      data = {
        id: selectedRowsdata,
        appid
      }
    }
    const res = await insuranceCreateExcel(data)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = '车衣保险.xlsx'
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
  }
  // 搜索
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      appid: localStorage.getItem('appid'),
      ...data
    }
    const res = await insuranceSerach(pageData)

    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  // 删除照片
  const deleteImgFn = (index) => {
    let imgData = [...fileList]
    imgData.splice(index, 1)
    setFileList(imgData)
  }
  const imgageChangeFn = (data) => {
    if (data.file.status == 'done') {
      setFileList([
        ...fileList,
        ...data.fileList.map((item) => {
          return item.response.image_url
        })
      ])
    }
  }
  return (
    <div>
      <Card>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div className="tabeleStyle">
          <Table
            rowSelection={{
              type: 'checkbox',
              ...rowSelection
            }}
            pagination={false}
            bordered
            rowKey="key"
            columns={columns}
            dataSource={dataSource}
          />
        </div>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      {/* 修改 */}
      <div>
        <Modal
          footer={[]}
          onCancel={() => {
            setIsShowAdd(false)
            form.resetFields()
            _id = ''
          }}
          open={isShowAdd}
        >
          <div className="Title center">酷德车膜电子保险卡</div>
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 7
            }}
            wrapperCol={{
              span: 16
            }}
            style={{
              maxWidth: 600
            }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item
              label="投保人："
              name="carOwnerName"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>

            <Form.Item
              label="联系方式："
              name="carOwnerPhone"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="批次号："
              name="filmNo"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="保单号："
              name="warrantyNum"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>

            <Form.Item
              label="米数"
              name="compensateNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="快递单号"
              name="trackingNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="图片："
              name="images"
              rules={[
                {
                  required: true,
                  message: '请选择'
                }
              ]}
            >
              <div>
                <div className="upImgBox align_center">
                  {fileList.map((item, index) => {
                    return (
                      <div className="imgBox center">
                        <img
                          style={{ width: '100%', height: '100%' }}
                          src={item}
                          alt=""
                        />
                        <div
                          className="mask center"
                          style={{ justifyContent: 'space-evenly' }}
                        >
                          <DeleteOutlined
                            onClick={() => {
                              deleteImgFn(index)
                            }}
                            style={{ fontSize: 20, color: '#FFFFFF' }}
                          />
                          <EyeOutlined
                            onClick={() => {
                              setMagnifyImg(item)
                              setIsImgShow(true)
                            }}
                            style={{ fontSize: 20, color: '#FFFFFF' }}
                          />
                        </div>
                      </div>
                    )
                  })}
                </div>
                <Upload
                  action={`${baseURL}api/uploadAvatar`}
                  listType="picture-card"
                  onChange={imgageChangeFn}
                  accept="image/png, image/jpeg"
                  showUploadList={false}
                  maxCount={1}
                >
                  <button
                    style={{
                      border: 0,
                      background: 'none'
                    }}
                    type="button"
                  >
                    <PlusOutlined />
                    <div
                      style={{
                        marginTop: 8
                      }}
                    ></div>
                  </button>
                </Upload>
              </div>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      <Modal
        open={isShowDetils}
        footer={[]}
        onCancel={() => {
          setisShowDetils(false)
        }}
      >
        <div className="detilsBox">
          <div className="Title center">酷德车膜理赔卡</div>
          <Row>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">补膜产品：</span>
              <span> {detilsData.filmName}</span>
            </Col>

            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保车辆：</span>
              <span> {detilsData.carName}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保日期：</span>
              <span> {detilsData.startTime}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">投保费用：</span>
              <span> {detilsData.price}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">联系人：</span>
              <span> {detilsData.carOwnerName}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">联系电话：</span>
              <span> {detilsData.carOwnerPhone}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">身份证号码：</span>
              <span> {detilsData.identity}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">剩余米数：</span>
              <span> {detilsData.product}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">赔付米数：</span>
              <span> {detilsDataApply.compensateNumber}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">保险编号：</span>
              <span> {detilsData.warrantyNum}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">受损部位：</span>
              <span> {detilsDataApply.damaged}</span>
            </Col>
            <Col style={{ margin: '3px 0' }} span={24}>
              <span className="detilsTitle">事故过程：</span>
              <span> {detilsDataApply.remark}</span>
            </Col>
          </Row>
          <div>
            {detilsDataApply.images
              ? JSON.parse(detilsDataApply.images).map((item, index) => {
                  return <Image key={index} width={'100%'} src={item} />
                })
              : ''}
          </div>
        </div>
        <div className="footButtonBoxCompen">
          {detilsDataApply.status == 0 ? (
            <div className="footButtonBox">
              <div
                className="footButton center"
                onClick={() => {
                  configApplyFn()
                }}
              >
                申请通过
              </div>
              <div
                className="footButton center"
                onClick={() => {
                  setisShowDetils(false)
                  setopposeRemarkSohw(true)
                }}
              >
                驳回理赔
              </div>
            </div>
          ) : (
            ''
          )}
        </div>
      </Modal>
      <div>
        <Modal
          footer={[]}
          onCancel={() => {
            setopposeRemarkSohw(false)
            form.resetFields()
            _id = ''
          }}
          open={opposeRemarkSohw}
        >
          <div className="Title center">酷德车膜电子卡</div>
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 7
            }}
            wrapperCol={{
              span: 16
            }}
            style={{
              maxWidth: 600
            }}
            onFinish={onFinishOpposeRemark}
            autoComplete="off"
          >
            <Form.Item
              label="驳回理由："
              name="opposeRemark"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <TextArea className="inputeStyle" />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {/* 发货 */}
      <div>
        <Modal
          footer={[]}
          onCancel={() => {
            setdeliverShow(false)
            form.resetFields()
            _id = ''
          }}
          open={deliverShow}
        >
          <div className="Title center">酷德车膜电子卡</div>
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 7
            }}
            wrapperCol={{
              span: 16
            }}
            style={{
              maxWidth: 600
            }}
            onFinish={onFinishTrackingNumber}
            autoComplete="off"
          >
            <Form.Item
              label="快递单号："
              name="trackingNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <TextArea className="inputeStyle" />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {/* 图片放大效果 */}
      <Modal
        open={isImgShow}
        footer={[]}
        onCancel={() => {
          setIsImgShow(false)
        }}
        closable={false}
      >
        <div>
          <img className="ImgShow" src={magnifyImg} alt="" srcset="" />
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
})
export default App
